package com.thekernel.youdaoyun.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.thekernel.youdaoyun.annotation.Log;
import com.thekernel.youdaoyun.bean.Note;
import com.thekernel.youdaoyun.bean.Star;
import com.thekernel.youdaoyun.exception.MyException;
import com.thekernel.youdaoyun.exception.impl.DataAlreadyExistsException;
import com.thekernel.youdaoyun.exception.impl.DataNotFoundException;
import com.thekernel.youdaoyun.exception.impl.SystemErrorException;
import com.thekernel.youdaoyun.mapper.NoteMapper;
import com.thekernel.youdaoyun.service.NoteService;
import com.thekernel.youdaoyun.service.StarService;
import com.thekernel.youdaoyun.util.FileUtils;
import com.thekernel.youdaoyun.util.ResponseUtils;
import com.thekernel.youdaoyun.util.UserUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author TheKernel
 * @Date 2019/9/13 7:42 下午
 * @Version 1.0
 * @Description 暴露给前端的收藏接口
 */
@Api(value = "收藏Controller")
@Controller
@RequestMapping("star")
public class StarController {

    @Autowired
    private StarService starService;

    @Autowired
    private NoteMapper noteMapper;

    /**
     * 用于测试 /star 接口是否可用
     * @return String
     */
    @ApiIgnore
    @GetMapping("hello")
    public @ResponseBody String index() {
        return "hello Star !!!";
    }

    /**
     * 添加收藏 API
     * @param star 收藏信息
     * @return String 是否成功以及相关信息
     */
//    @Log("star_add")
    @ApiOperation(value = "添加收藏", notes = "根据用户信息以及笔记内容添加用户收藏")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "StarNote", value = "笔记名", required = true, dataType = "String", paramType = "form"),
    })
    @PostMapping("addStar")
    public @ResponseBody String addStar(@RequestBody Star star) throws MyException{
        long userId = UserUtils.checkReturnUserId();
        // 生成 star
        star.setStarUser(userId);
        // 添加收藏
        int result = this.starService.addStar(star);
        // Response Body
        if (result > 0) {
            JSONObject returnData = new JSONObject();
            returnData.put("starId", star.getStarId());
            return ResponseUtils.response(ResponseUtils.SUCCESS, "Add Star Success !!!", returnData);
        } else if (result == 0) {
            throw new DataAlreadyExistsException();
        } else if (result == -1) {
            throw new DataNotFoundException();
        } else {
            throw new SystemErrorException();
        }
    }

    /**
     * 取消收藏 API
     * @param star 收藏
     * @return String 是否成功以及相关信息
     */
//    @Log("star_cancel")
    @ApiOperation(value = "取消收藏", notes = "根据用户信息以及笔记内容取消用户收藏")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "starId", value = "star的id", required = true, dataType = "String", paramType = "form")
    })
    @DeleteMapping("cancelStar")
    public @ResponseBody String cancelStar(@RequestBody Star star) throws MyException {
        long userId = UserUtils.checkReturnUserId();
        // 取消 star
        int result = this.starService.cancelStar(star.getStarId(), userId);
        if (result == 1) {
            return ResponseUtils.response(ResponseUtils.SUCCESS, "Cancel Star Success !!!", null);
        } else if (result == 0) {
            throw new DataAlreadyExistsException();
        } else if (result == -1) {
            throw new DataNotFoundException();
        } else {
            throw new SystemErrorException();
        }
    }

    /**
     * 查询收藏 API
     * @return 收藏列表
     * @throws MyException 查询错误等
     */
//    @Log("star_query")
    @ApiOperation(value = "查询收藏", notes = "根据用户信息查询用户收藏")
    @GetMapping("queryStar")
    public @ResponseBody String queryStar() throws MyException {
        Star[] stars = this.starService.queryStar();
        List<JSONObject> starNotes = new ArrayList<>();
        JSONObject returnData = new JSONObject();

        for (Star star: stars) {
            JSONObject tmp = new JSONObject();
            Note note = this.noteMapper.queryValidNoteByNoteId(star.getStarNote());
            if (note == null) {
                continue;
            }
            tmp.put("starId", star.getStarId());
            tmp.put("noteId", note.getNoteId());
            tmp.put("noteTitle", note.getNoteTitle());
            tmp.put("noteContent", FileUtils.readFile(note.getNoteContent()));
            tmp.put("status", note.getStatus());
            tmp.put("createTime", note.getCreateTime());
            tmp.put("type", note.getType());
            tmp.put("folder", note.getFolder() ? 1 : 0);

            starNotes.add(tmp);
        }

        returnData.put("data", starNotes);
        returnData.put("num", starNotes.size());
        return ResponseUtils.response(
                ResponseUtils.SUCCESS,
                "Query Newest Notes Success",
                returnData)
                ;
    }


}
